from flask import Blueprint, render_template, request, redirect, url_for, g
from exts import db
from models import Work_assign, Exam, Student_Exam, teacherModel, stuAns
# 这里定义的权限视图函数url前缀为"/exam"
bp = Blueprint("tea", __name__, url_prefix="/tea")


@bp.route('/')
def teaIndex():
    # TODO 后续修改成分发任务
    exams = Exam.query.all()
    teacher = teacherModel.query.get(g.user.id)
    print(exams)
    # 更新判卷子状态
    for exam in exams:
        wa = Work_assign.query.filter_by(
            exam_id=exam.id, teacher_id=teacher.id).first()
        count = Student_Exam.query.filter_by(
            exam_id=exam.id, finished='1').count()
        if wa is None:
            wa = Work_assign(work_finished=0, work_count=count)
            wa.wa_exam = exam
            teacher.exams.append(wa)
        else:
            wa.work_count = count
        db.session.commit()
    works = Work_assign.query.filter_by(teacher_id=teacher.id).all()
    work_infos = []
    for work in works:
        cur_exam = Exam.query.get(work.exam_id)
        work_infos.append((cur_exam, work))
    print(work_infos)
    return render_template('tea.html', work_infos=work_infos)


@bp.route('/judge_exam/<int:exam_id>', methods=['GET', 'POST'])
def judgeExam(exam_id):
    exam = Exam.query.get(exam_id)
    teacher = teacherModel.query.get(g.user.id)
    questions = []
    wa = Work_assign.query.filter_by(
        exam_id=exam.id, teacher_id=teacher.id).first()
    stu_anss = stuAns.query.filter_by(exam_id=exam.id).all()
    print(stu_anss)
    for question in exam.questions:
        if question.question_type == 2:
            questions.append(question)
    if request.method == 'GET':
        # 后面改成可以显示多个题,这里只显示一个
        wa.work_finished += 1
        print(wa.work_finished)
        db.session.commit()
        return render_template('paperMark.html', exam=exam, wa=wa,
                               questions=questions[0], stu_anss=stu_anss[wa.work_finished-1])
    else:
        # TODO 将分数录入数据库
        return redirect(url_for('tea.teaIndex'))
